<template>
	<view class="page">
		<view class="camera-container">
			<camera 
				class="camera" 
				:device-position="devicePosition" 
				flash="off"
				@error="onCameraError"
			></camera>
			<view class="controls">
				<view class="control-btn" @tap="switchCamera">
					<uni-icons type="loop" size="28" color="#fff"></uni-icons>
				</view>
				<view class="record-btn" @touchstart="startRecord" @touchend="stopRecord">
					<view class="record-inner" :class="{ 'recording': isRecording }"></view>
				</view>
				<view class="control-btn" @tap="chooseFromAlbum">
					<uni-icons type="image" size="28" color="#fff"></uni-icons>
				</view>
			</view>
			<view class="timer" v-if="isRecording">
				<text>{{ formatTime(recordTime) }}</text>
			</view>
		</view>
		<view class="preview-section" v-if="videoPath">
			<video 
				class="preview-video" 
				:src="videoPath" 
				:controls="true"
				object-fit="cover"
			></video>
			<view class="preview-actions">
				<button class="btn btn-cancel" @tap="cancelVideo">重拍</button>
				<button class="btn btn-confirm" @tap="confirmVideo">使用</button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const devicePosition = ref('back')
const isRecording = ref(false)
const recordTime = ref(0)
const videoPath = ref('')
let recordTimer = null
let cameraContext = null

// 初始化相机
onMounted(() => {
	cameraContext = uni.createCameraContext()
})

// 切换摄像头
function switchCamera() {
	devicePosition.value = devicePosition.value === 'back' ? 'front' : 'back'
}

// 开始录制
function startRecord() {
	if (isRecording.value) return
	
	isRecording.value = true
	recordTime.value = 0
	
	cameraContext.startRecord({
		success: () => {
			recordTimer = setInterval(() => {
				recordTime.value++
				// 最长60秒
				if (recordTime.value >= 60) {
					stopRecord()
				}
			}, 1000)
		},
		fail: (err) => {
			console.error('开始录制失败:', err)
			uni.showToast({ title: '开始录制失败', icon: 'none' })
			isRecording.value = false
		}
	})
}

// 停止录制
function stopRecord() {
	if (!isRecording.value) return
	
	cameraContext.stopRecord({
		success: (res) => {
			isRecording.value = false
			if (recordTimer) {
				clearInterval(recordTimer)
				recordTimer = null
			}
			videoPath.value = res.tempVideoPath
		},
		fail: (err) => {
			console.error('停止录制失败:', err)
			uni.showToast({ title: '停止录制失败', icon: 'none' })
			isRecording.value = false
			if (recordTimer) {
				clearInterval(recordTimer)
				recordTimer = null
			}
		}
	})
}

// 从相册选择
function chooseFromAlbum() {
	uni.chooseVideo({
		sourceType: ['album'],
		maxDuration: 60,
		compressed: true,
		success: (res) => {
			videoPath.value = res.tempFilePath
		},
		fail: () => {
			uni.showToast({ title: '选择视频失败', icon: 'none' })
		}
	})
}

// 确认使用视频
function confirmVideo() {
	if (!videoPath.value) {
		uni.showToast({ title: '请先拍摄或选择视频', icon: 'none' })
		return
	}
	
	// 跳转到上传页面
	const path = encodeURIComponent(videoPath.value)
	const duration = recordTime.value || 0
	uni.navigateTo({ 
		url: `/pages/publish/create?path=${path}&duration=${duration}` 
	})
}

// 取消视频
function cancelVideo() {
	videoPath.value = ''
	recordTime.value = 0
}

// 格式化时间
function formatTime(seconds) {
	const m = Math.floor(seconds / 60)
	const s = seconds % 60
	return `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
}

// 相机错误
function onCameraError(err) {
	console.error('相机错误:', err)
	uni.showToast({ title: '相机初始化失败', icon: 'none' })
}

onUnmounted(() => {
	if (recordTimer) {
		clearInterval(recordTimer)
	}
})
</script>

<style scoped>
.page {
	width: 100vw;
	height: 100vh;
	background: #000;
	position: relative;
}

.camera-container {
	width: 100%;
	height: 100%;
	position: relative;
}

.camera {
	width: 100%;
	height: 100%;
}

.controls {
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	align-items: center;
	justify-content: space-around;
	padding: 40rpx 60rpx;
	padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
	background: linear-gradient(180deg, rgba(0,0,0,0), rgba(0,0,0,.8));
}

.control-btn {
	width: 80rpx;
	height: 80rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 50%;
}

.record-btn {
	width: 120rpx;
	height: 120rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: rgba(255, 255, 255, 0.3);
	border-radius: 50%;
	border: 8rpx solid #fff;
}

.record-inner {
	width: 80rpx;
	height: 80rpx;
	background: #ff3b30;
	border-radius: 50%;
	transition: all 0.3s;
}

.record-inner.recording {
	border-radius: 8rpx;
	width: 60rpx;
	height: 60rpx;
}

.timer {
	position: absolute;
	top: 100rpx;
	left: 50%;
	transform: translateX(-50%);
	background: rgba(0, 0, 0, 0.6);
	padding: 12rpx 24rpx;
	border-radius: 40rpx;
}

.timer text {
	color: #fff;
	font-size: 32rpx;
	font-weight: 600;
}

.preview-section {
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background: #000;
	display: flex;
	flex-direction: column;
}

.preview-video {
	width: 100%;
	flex: 1;
}

.preview-actions {
	display: flex;
	gap: 20rpx;
	padding: 30rpx;
	padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
	background: rgba(0, 0, 0, 0.8);
}

.btn {
	flex: 1;
	height: 88rpx;
	border-radius: 12rpx;
	font-size: 32rpx;
	font-weight: 600;
	border: none;
}

.btn-cancel {
	background: rgba(255, 255, 255, 0.2);
	color: #fff;
}

.btn-confirm {
	background: linear-gradient(135deg, #ff2d55, #ff6a00);
	color: #fff;
}
</style>

